<template>
  <!-- 质量月报树 -->
  <tree-search
    v-bind="$attrs"
    v-on="$listeners"
    @drop="handleDrop"
    @dragenter="$console(1)"
    ref="treeSearch"
    emptyDescription="暂无质量管理信息"
    :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
    :api="apiTree"
    :isAll="false"
    :query="{ id: $route.query.treeId,isLook:$route.query.isLook }"
    :selectedKeys.sync="selectedKeys"
    :selectOptions.sync="selectOptions"
  >
    <slot name="after" :data="data" slot="nameAfter" slot-scope="{ data }" />
  </tree-search>
</template>

<script>
import TreeSearch from '@/components/businessComponents/TreeSearch' // 树
import { getTree } from '@/api/quality/qualityMonth' // api

export default {
  name: 'TreeQuality',
  components: {
    TreeSearch
  },
  props: {
    // 是否显示停用按钮的控件
    showEnabled: {
      type: Boolean,
      default: () => false
    }
  },
  computed: {
    // 树节点api
    apiTree() {
      return {
        getList: getTree
      }
    }
  },
  data() {
    return {
      selectedKeys: [], // 选中节点id集合
      selectOptions: {} // 选中节点业务对象
    }
  },
  methods: {
    // 渲染列表
    getList() {
      return this.$refs.treeSearch.getList()
    },
    // 拖拽树节点落下时
    handleDrop(info) {
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])

      // Find dragObject
      if (info.dropToGap && info.node.dataRef.parentId === info.dragNode.dataRef.parentId) {
        const data = info.node.$parent.dataRef.children
        let dragObj
        // 删除拖拽的节点，且缓存节点
        data.forEach((item, index) => {
          if (item.id === dragKey) {
            data.splice(index, 1)
            dragObj = item
          }
        })
        let i = data.findIndex((i) => i.id === dropKey) // 拖拽落下节点的索引值
        if (dropPosition === -1) {
          data.splice(i, 0, dragObj)
        } else {
          data.splice(i + 1, 0, dragObj)
        }
        // console.log(info.node.$parent.dataRef.children.map((i) => i.name))
        this.$emit('update:treeData', this.$refs.treeSearch.treeData)
      } else {
        this.$message.warning('只可在当前层级拖拽！')
      }
    }
  },
  watch: {
    selectedKeys(e) {
      this.$emit('update:selectedKeys', e)
    },
    selectOptions(e) {
      this.$emit('update:selectOptions', e)
    }
  }
}
</script>
